package com.lz.hbase;

import com.alibaba.fastjson.JSONObject;
import com.lz.es.EsPage;
import com.lz.es.EsTool;
import org.apache.hadoop.hbase.TableName;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

/**
 * @description
 *
 * @date 2021-11-25 22:31
 *
 * @author Lizhong
 */
public class IOTApp {

    static TableName tbName = HbaseTest.getTbName("IOT_TABLE");
    static EsTool instance = EsTool.getInstance();

    public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
        // main0();
        matchPK();
    }

    private static void main0() {
        // clear();
        // create(instance);
        // insert();

        // multiQuery(instance);
        EsPage esPage = new EsPage();
        // page.getALL();
        // search(esPage);
        // instance.queryAll("iot");
        // List<JSONObject> type0 = HbaseTest.scan(tbName, "type0", "1");
        // System.out.println(type0);
        // int size = HbaseTest.getALl(tbName, HbaseTest.COLUMNS_FAMILY_1).size();
        // System.out.println(size);
    }

    public static void matchPK() throws IOException, ExecutionException, InterruptedException {
        // clear();
        // create(instance);
        IOT iot0 = new IOT("I am chinese ", "I am japan", System.nanoTime() + "", "people01", "I am japan ");
        IOT iot1 = new IOT("I am chinese1 ", "I am japan2", System.nanoTime() + "", "people02", "I am japan ");
        List<IOT> iots = Arrays.asList(iot0, iot1);
        List<JSONObject> json = iots.stream().map(v -> JSONObject.parseObject(JSONObject.toJSON(v).toString())).collect(Collectors.toList());
        instance.bulkIndexDocument("iot", "_doc", json);

        TransportClient client = EsTool.getInstance().getClient();

        // match + text  有相交就可以
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.matchQuery("value", "I am dd"));
        SearchResponse response = client.prepareSearch("iot").setQuery(queryBuilder).execute().get();
        System.out.println(response.getHits().getTotalHits());
        // match + keyword  必须一模一样,长短都不行
        queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.matchQuery("type0", "I am chinese "));
        response = client.prepareSearch("iot").setQuery(queryBuilder).execute().get();
        System.out.println(response.getHits().getTotalHits());

        // match_phrase + text  有序子集
        queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.matchPhraseQuery("value", "I am dd"));
        response = client.prepareSearch("iot").setQuery(queryBuilder).execute().get();
        System.out.println(response.getHits().getTotalHits());

        queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.matchPhraseQuery("value", "I am chinese "));
        response = client.prepareSearch("iot").setQuery(queryBuilder).execute().get();
        System.out.println(response.getHits().getTotalHits());

        // match_phrase + keyword 必须一模一样
        queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.matchPhraseQuery("type0", "I am dd"));
        response = client.prepareSearch("iot").setQuery(queryBuilder).execute().get();
        System.out.println(response.getHits().getTotalHits());

        queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.matchPhraseQuery("type0", "I am chinese "));
        response = client.prepareSearch("iot").setQuery(queryBuilder).execute().get();
        System.out.println(response.getHits().getTotalHits());

        // queryStringQuery + text  无序子集
        queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.queryStringQuery( "I am dd").field("value"));
        response = client.prepareSearch("iot").setQuery(queryBuilder).execute().get();
        System.out.println(response.getHits().getTotalHits());

        queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.queryStringQuery("I japan ").field("value"));
        response = client.prepareSearch("iot").setQuery(queryBuilder).execute().get();
        System.out.println(response.getHits().getTotalHits());

        // queryStringQuery + keyword 一直不能命中
        queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.queryStringQuery("I am dd").field("type0"));
        response = client.prepareSearch("iot").setQuery(queryBuilder).execute().get();
        System.out.println(response.getHits().getTotalHits());

        queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.queryStringQuery( "I am chinese ").field("type0"));
        response = client.prepareSearch("iot").setQuery(queryBuilder).execute().get();
        System.out.println(response.getHits().getTotalHits());

        // queryStringQuery + text  无序子集
        queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.queryStringQuery( "I am dd").field("value"));
        response = client.prepareSearch("iot").setQuery(queryBuilder).execute().get();
        System.out.println(response.getHits().getTotalHits());

        queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.queryStringQuery("I japan ").field("value"));
        response = client.prepareSearch("iot").setQuery(queryBuilder).execute().get();
        System.out.println(response.getHits().getTotalHits());

        // term + keyword 两者都不分词，所以必须一模一样,空格不能多，不能少
        queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.termQuery("type0" ,"I am chinese"));
        response = client.prepareSearch("iot").setQuery(queryBuilder).execute().get();
        System.out.println(response.getHits().getTotalHits());

        queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.termQuery("type0" ,"I am chinese "));
        response = client.prepareSearch("iot").setQuery(queryBuilder).execute().get();
        System.out.println(response.getHits().getTotalHits());

        // term + text term(空格不能多，不能少)必须是分词后的一个
        queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.termQuery("value" ,"I am japan sds"));
        response = client.prepareSearch("iot").setQuery(queryBuilder).execute().get();
        System.out.println(response.getHits().getTotalHits());

        queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.termQuery("value" ,"japan"));
        response = client.prepareSearch("iot").setQuery(queryBuilder).execute().get();
        System.out.println(response.getHits().getTotalHits());

    }

    private static void search(EsPage esPage) {
        SearchResponse searchResponse = esPage.createScroll("Device_7", "1", 4, null);
        String scrollId = searchResponse.getScrollId();
        Arrays.stream(searchResponse.getHits().getHits()).forEach(System.out::println);
        System.out.println("====================================");
        searchResponse = esPage.createScroll("Device_7", "1", 4, scrollId);
        Arrays.stream(searchResponse.getHits().getHits()).forEach(System.out::println);
    }

    private static void insert() throws IOException {
        int times = 50000;
        Random random = new Random();
        long l = System.currentTimeMillis();
        List<IOT> iots = new ArrayList<>();
        for (long i = l; i < l + times; i++) {
            IOT iot = new IOT(random.nextInt(5) + "", i % 10 + "", System.nanoTime() + "", i + "", "Device_" + i % 9);
            iots.add(iot);
        }
        List<JSONObject> json = iots.stream().map(v -> JSONObject.parseObject(JSONObject.toJSON(v).toString())).collect(Collectors.toList());
        HbaseTest.batchInsertData(tbName, iots);
        instance.bulkIndexDocument("iot", "_doc", json);
    }

    private static void clear() {
        try {
            instance.deleteIndexAndMapping("iot");

        } catch (Exception e) {
            System.out.println("删除错误");
        }
        try {
            HbaseTest.deleteTable(tbName);
        } catch (Exception e) {
            System.out.println(e);
            System.out.println("删除hbase失败");
        }
    }

    private static void multiQuery(EsTool instance) {
        RangeQueryBuilder rangequerybuilder = QueryBuilders
                //传入时间，目标格式2020-01-02T03:17:37.638Z
                .rangeQuery("time")
                .from("1205192388126600");

        SearchResponse searchResponse = instance.getClient().prepareSearch("iot").setQuery(
                QueryBuilders.boolQuery()
                        //must表示and
                        .must(rangequerybuilder) //根据时间范围查询
                        // .must(QueryBuilders.existsQuery("api_id"))
                        .must(QueryBuilders.matchPhraseQuery("Device_1", "1"))
                        .must(QueryBuilders.matchQuery("deviceId", "Device_1"))
        ).setExplain(true).execute().actionGet();
        for (SearchHit searchHit : searchResponse.getHits()) {
            System.out.println(searchHit);
        }
    }


    private static void create(EsTool instance) throws IOException {

        HbaseTest.createTable(tbName, new String[]{HbaseTest.COLUMNS_FAMILY_1});
        String jsonString = "{\"properties\":" +
                "{" +
                "\"type0\":{\"type\":\"keyword\"}," +
                "\"deviceId\":{\"type\":\"keyword\"}," +
                "\"value\":{\"type\":\"text\"}," +
                "\"time\":{\"type\":\"text\"}" +
                "}" +
                "}";
        instance.createIndexAndMapping("iot", jsonString);
    }
}
